package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SendSms;
import com.itheima.reggie.dto.UserLoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.RedisKeys;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @author kcs
 * @date 2021/11/27
 * @TIME:16:37
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R SendMsg(@RequestBody User user, HttpServletRequest request){

        //数据校验

        //生成验证码
        //String code = ValidateCodeUtils.generateValidateCode4String(6); //带字母
        Integer code = ValidateCodeUtils.generateValidateCode(4); //纯数字
        System.out.println(code);

        //发送短信
        //SendSms.sendMsg(user.getPhone(),code+"");

        //4.0将验证码存储在session中
        //HttpSession session = request.getSession();
        //session.setAttribute(user.getPhone(),code+"");

        //4.1将验证码存储在redis中 -- 设置时效性
        redisTemplate.opsForValue().set(RedisKeys.RG_CODE+user.getPhone(),code+"",5, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    /**
     * 验证码登录
     * @param userLoginDto
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody UserLoginDto userLoginDto,HttpServletRequest request){

        //1.获取前端传递的手机号和验证码
        if(null == userLoginDto){
            return R.error("参数异常");
        }

        HttpSession session = request.getSession();

        //2.1从Session中获取到手机号对应的正确的验证码
        //String sessionCode = (String) session.getAttribute(userLoginDto.getPhone());

        //2.2从redis中获取到手机号对应的正确的验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(RedisKeys.RG_CODE + userLoginDto.getPhone());

        //3.验证码校验
        if(null == sessionCode || sessionCode == ""){
            return R.error("请先获取验证码");
        }

        //4.对比验证码,若匹配失败,提示错误信息
        if(!sessionCode.equals(userLoginDto.getCode())){
            return R.error("验证码错误");
        }

        //4.1若匹配成功,查看数据库中是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,userLoginDto.getPhone());
        User user = userService.getOne(wrapper);

        //4.2若不存在,进行注册
        if(user == null){
            user = new User();
            user.setPhone(userLoginDto.getPhone());
            userService.save(user);
        }

        //5.0若存在,登录成功,将session中的code清理,将登录用户的id存入session中
        //session.removeAttribute(userLoginDto.getPhone());

        //5.1若存在,登录成功,将redis中的code清理,将登录用户的id存入session中
        redisTemplate.delete(RedisKeys.RG_CODE+userLoginDto.getPhone());
        session.setAttribute("user",user.getId());
        return R.success("登录成功");
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/loginout")
    public R logout(HttpServletRequest request){

        //清理session中的user信息
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
